//
//  FortuneRecordController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/21.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "FortuneRecordController.h"
#import "FortuneRecordCell.h"
#import "FortuneRecordModel.h"

@interface FortuneRecordController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) IBOutlet UIView *leftBackgroundView;
@property (strong, nonatomic) IBOutlet UILabel *totalLabel;
@property (strong, nonatomic) IBOutlet UILabel *orderNOLabel;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic,assign)NSInteger page;
@property (strong, nonatomic) IBOutlet UIView *dateSelectView;
@property (strong, nonatomic) IBOutlet UIDatePicker *datePicker;
@property (strong, nonatomic) IBOutlet UIButton *starTimeBtn;
@property (strong, nonatomic) IBOutlet UIButton *endTimeBtn;
@property (nonatomic, copy) NSString *stardate;
@property (nonatomic, copy) NSString *enddate;

@end

@implementation FortuneRecordController
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"赚钱记录";
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:[UIImage imageNamed:@"返回箭头"] actionBlock:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    self.headerView.height = 314 * (ScreenWidth / 375);
    self.tableView.tableHeaderView = self.headerView;
    [self.tableView registerNib:[UINib nibWithNibName:@"FortuneRecordCell" bundle:nil] forCellReuseIdentifier:@"FortuneRecordCell"];
    // 添加上拉刷新控件
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreData)];
    
    // 添加下拉刷新控件
    [self.tableView addHeaderWithTarget:self action:@selector(loadOnePageData)];
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    [self.endTimeBtn setTitle:dateString forState:UIControlStateNormal];
    self.enddate = dateString;
    
    NSDate *starDate = [NSDate dateWithTimeIntervalSinceNow:-30*24*60*60];
    NSDateFormatter *starDateFormatter = [[NSDateFormatter alloc] init];
    [starDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *starDateString = [dateFormatter stringFromDate:starDate];
    [self.starTimeBtn setTitle:starDateString forState:UIControlStateNormal];
    self.stardate = starDateString;
    self.datePicker.maximumDate = currentDate;
    [self loadOnePageData];
}

- (void)loadMoreData
{
    self.page++;
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];
    [self webRequest_GetMakeMoneyInfoStartdate:self.starTimeBtn.titleLabel.text Enddate:self.endTimeBtn.titleLabel.text Page:page];
}

- (void)loadOnePageData
{
    self.page = 1;
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];
    [self webRequest_GetMakeMoneyInfoStartdate:self.starTimeBtn.titleLabel.text Enddate:self.endTimeBtn.titleLabel.text Page:page];
}

// 开始时间
- (IBAction)starTimeBtn:(UIButton *)sender {
    self.endTimeBtn.selected = NO;
    self.starTimeBtn.selected = YES;
    self.dateSelectView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self.view.window addSubview:self.dateSelectView];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSString *str = self.starTimeBtn.titleLabel.text;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date1 = [formatter dateFromString:str];
    [self.datePicker setDate:date1];
}

// 结束时间
- (IBAction)endTimeBtn:(UIButton *)sender {
    self.starTimeBtn.selected = NO;
    self.endTimeBtn.selected = YES;
    self.dateSelectView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self.view.window addSubview:self.dateSelectView];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSString *str = self.endTimeBtn.titleLabel.text;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date1 = [formatter dateFromString:str];
    [self.datePicker setDate:date1];
}

- (IBAction)dateBackgroundButtonAction:(UIButton *)sender {
    
    [self.dateSelectView removeFromSuperview];
}

 /**
 *  确定按钮
 */
- (IBAction)makeSureBtn:(UIButton *)sender {
    
    NSDate *select = [self.datePicker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateAndTime =  [dateFormatter stringFromDate:select];
    if (self.starTimeBtn.selected) {
        [self.starTimeBtn setTitle:dateAndTime forState:UIControlStateNormal];
        self.stardate = dateAndTime;
        [self.dateSelectView removeFromSuperview];
        [self webRequest_GetMakeMoneyInfoStartdate:self.stardate Enddate:self.enddate Page:@"10000"];
        
    } else {
        [self.endTimeBtn setTitle:dateAndTime forState:UIControlStateNormal];
        self.enddate = dateAndTime;
        [self.dateSelectView removeFromSuperview];
        [self webRequest_GetMakeMoneyInfoStartdate:self.stardate Enddate:self.enddate Page:@"10000"];
    }
}

#pragma mark -- 网络请求 --
-(void)webRequest_GetMakeMoneyInfoStartdate:(NSString *)startdate Enddate:(NSString *)enddate
                                       Page:(NSString *)page
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"正在加载...";
    [self.view addSubview:hud];
    [hud show:YES];
    __weak typeof(self)weakself = self;
    NSString *uidStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserIdKey];
    NSDictionary *dict = @{@"page": page,@"uid":uidStr,@"startdate" : startdate, @"enddate" : enddate};
    [HttpRequestManager getMethod:KMakeMoneyInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            if (self.page == 1) {
                [self.dataSource removeAllObjects];
            }
            self.dataSource = nil;
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (response[@"data"][@"totalmoney"] != 0) {
                self.totalLabel.text = [NSString stringWithFormat:@"共赚取%@元",response[@"data"][@"totalmoney"]];
            }
            if (response[@"data"][@"ordernum"] != 0) {
                self.orderNOLabel.text = [NSString stringWithFormat:@"订单%@个",response[@"data"][@"ordernum"]];
            }
            NSMutableArray *ary = response[@"data"][@"recordlist"];
            for (NSMutableDictionary *dic in ary) {
                FortuneRecordModel *model = [MTLJSONAdapter modelOfClass:[FortuneRecordModel class] fromJSONDictionary:dic error:nil];
                [weakself.dataSource addObject:model];
            }
            [weakself.tableView reloadData];
            
        }else{
            [[[UIAlertView alloc]initWithTitle:@"提示" message:@"所选时间段内没有订单" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]show];
        }
        [weakself.tableView footerEndRefreshing];
        [weakself.tableView headerEndRefreshing];
    }];
}

#pragma mark ---tableViewDelegate---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"FortuneRecordCell";
    FortuneRecordCell *cell= [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"FortuneRecordCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    
    FortuneRecordModel *model = self.dataSource[indexPath.row];
    cell.fortuneRecordModel = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView reloadData];
    
    
    
}

//返回cell的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
